package com.mutual.index.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.javassist.compiler.MemberResolver.Method;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Maps;
import com.mutual.app.pojo.AppResult;
import com.mutual.appUserInfo.pojo.AppUserInfoProduct;
import com.mutual.appUserInfo.service.AppUserInfoProductService;
import com.mutual.appUserInfo.service.AppUserInfoService;
import com.mutual.attachment.service.AttachmentService;
import com.mutual.commom.pojo.ReturnResult;
import com.mutual.commom.service.RedisService;
import com.mutual.commom.util.DateUtil;
import com.mutual.commom.util.JSONUtil;
import com.mutual.commom.util.SMSUtil;
import com.mutual.commom.util.SystemUtil;
import com.mutual.commom.zfb.AlipayConfig;
import com.mutual.family.pojo.Family;
import com.mutual.family.service.FamilyService;
import com.mutual.healthInfo.pojo.HealthInfo;
import com.mutual.healthInfo.service.HealthInfoService;
import com.mutual.invite.service.InviteService;
import com.mutual.product.pojo.Product;
import com.mutual.product.service.ProductService;
import com.mutual.vipAnnualFee.pojo.VipAnnualFee;
import com.mutual.vipAnnualFee.service.VipAnnualFeeService;

/**
 * 主界面
 * 
 * @author asus
 *
 */
@Controller
@RequestMapping("/payment")
public class PaymentController {

	@Resource
	private AppUserInfoService appUserInfoService;

	@Resource
	private AppUserInfoProductService appUserInfoProductService;

	@Resource
	private FamilyService familyService;

	@Resource
	private InviteService inviteService;

	@Resource
	private ProductService productService;

	@Resource
	private AttachmentService attachmentService;

	@Resource
	private HealthInfoService healthInfoService;

	@Resource
	private VipAnnualFeeService vipAnnualFeeService;

	@Resource
	private RedisService redisService;

	private static final Logger log = LoggerFactory.getLogger(PaymentController.class);


	/**
	 * 购买产品支付宝支付
	 * 
	 * @param obj
	 * @return
	 * @throws IOException 
	 */
	@GetMapping("buyProductPayZfb")
	@ResponseBody
	public void buyProductPayZfb(@RequestParam Map<String, Object> param, 
			HttpServletResponse response,AppUserInfoProduct appUserInfoProduct) throws IOException {
		Date vNow = new Date();
		String WIDout_trade_no = "";
		WIDout_trade_no += vNow.getYear();
		WIDout_trade_no += vNow.getMonth() + 1;
		WIDout_trade_no += vNow.getDate();
		WIDout_trade_no += vNow.getHours();
		WIDout_trade_no += vNow.getSeconds();
		WIDout_trade_no += vNow.getTime();
		response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
		appUserInfoProduct.setOrderNum(WIDout_trade_no);
		ReturnResult result=appUserInfoProductService.buyProduct(appUserInfoProduct);
		log.info("buyProductPayZfb 内部保存返回数据：{}",JSONUtil.getJSONFromObj(result));
		if(result.getStatus()!=ReturnResult.STATUS_SUCCESS){
			log.info(result.getReturnMsg().toString());
			response.getWriter().write(result.getReturnMsg().toString());// 直接将完整的表单html输出到页面
			response.getWriter().flush();
			response.getWriter().close();
			return;
		}
		AppUserInfoProduct selectData=(AppUserInfoProduct)result.getData();
		String WIDtotal_amount = String.valueOf(selectData.getAmount());
		String WIDsubject = "关爱筹支付";
		String WIDbody = "关爱筹支付";

		// 销售产品码 必填
		String product_code = "QUICK_WAP_WAY";
		/**********************/
		// SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
		// 调用RSA签名方式
		AlipayClient client = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
				AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
		AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

		// 封装请求支付信息
		AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
		model.setOutTradeNo(WIDout_trade_no);
		model.setSubject(WIDsubject);
		model.setTotalAmount(WIDtotal_amount);
		model.setBody(WIDbody);
		model.setTimeoutExpress("2m");
		model.setProductCode(product_code);
		alipay_request.setBizModel(model);
		// 设置异步通知地址
		alipay_request.setNotifyUrl(AlipayConfig.notify_app_url);
		alipay_request.setReturnUrl(AlipayConfig.return_app_url);
		// form表单生产
		String body = "";
		try {
			// 调用SDK生成表单
			body = client.pageExecute(alipay_request).getBody();
			log.info(AlipayConfig.notify_app_url);
			log.info(body);
			response.getWriter().write(body);// 直接将完整的表单html输出到页面
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("支付接口出错:", e);
		}
	}
	/**
	 * 支付宝异步提醒
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws AlipayApiException
	 */
	@RequestMapping(value = "/zhiFuBaoNotifyAction",method = RequestMethod.POST)
	@ResponseBody
	public void zhiFuBaoNotifyAction(HttpServletRequest request,HttpServletResponse response)
			throws IOException, AlipayApiException {
		log.info("-----------------zhiFuBaoNotifyAction 开始回调-----------------");
		AppUserInfoProduct appUserInfoProduct=new AppUserInfoProduct();
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		log.info("支付宝异步通知结果：{}",JSONUtil.getJSONFromMap(requestParams));
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}

		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
		// 计算得出通知验证结果
		// boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
		// publicKey, String charset, String sign_type)
		boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.CHARSET,
				"RSA2");

		if (verify_result) {// 验证成功
			//////////////////////////////////////////////////////////////////////////////////////////
			// 请在这里加上商户的业务逻辑程序代码

			// ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

			if (trade_status.equals("TRADE_FINISHED")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				// 如果有做过处理，不执行商户的业务程序

				// 注意：
				// 如果签约的是可退款协议，退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
				// 如果没有签约可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
			} else if (trade_status.equals("TRADE_SUCCESS")) {
				// 判断该笔订单是否在商户网站中已经做过处理
				// 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
				// 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
				// 如果有做过处理，不执行商户的业务程序

				// 注意：
				// 如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
			}
			String out_trade_no = request.getParameter("out_trade_no");
			appUserInfoProduct.setOrderNum(out_trade_no);
			appUserInfoProduct.setStatus(AppUserInfoProduct.STATUS_BUY_SUCCESS);
			appUserInfoProduct.setApplyDate(new Date());
			log.info("out_trade_no : {} 支付宝支付成功",out_trade_no);
		} else {// 验证失败
			response.getWriter().println("fail");
			appUserInfoProduct.setStatus(AppUserInfoProduct.STATUS_BUY_FAILED);
		    log.info("支付宝支付失败");
		}
		appUserInfoProductService.updateBuyProductStatus(appUserInfoProduct);
	}

	@RequestMapping(value = "/returnZhiFuBao",method = RequestMethod.GET)
	@ResponseBody
	public void returnZhiFuBao(HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
		response.getWriter().write("");// 直接将完整的表单html输出到页面
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	/**
	 * 查询支付状态
	 * @param appUserInfoProduct
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/selectPaymentStatus",method = RequestMethod.POST)
	@ResponseBody
	public AppResult selectPaymentStatus(AppUserInfoProduct appUserInfoProduct) throws IOException{
		List<AppUserInfoProduct> appUserInfoProducts=appUserInfoProductService
				.selectAppUserInfoProductList(appUserInfoProduct);
		AppResult appResult=new AppResult();
		if(appUserInfoProducts.isEmpty()){
			appResult.setStatus(AppResult.STATUS_FAILED);
		}else{
			appResult.setData(appUserInfoProducts.get(0));
		}
		return appResult;
	}
}
